package com.xqboss.apps.controller.test;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.cloudauth20190307.models.DescribeFaceVerifyResponse;
import com.xqboss.apps.domain.consumer.ConsumerRealName;
import com.xqboss.apps.domain.equipment.Equipment;
import com.xqboss.apps.dto.market.AddMarketDto;
import com.xqboss.apps.dto.market.MarketDto;
import com.xqboss.apps.dto.order.TradeResultDto;
import com.xqboss.apps.dto.order.WalletPayDto;
import com.xqboss.apps.dto.user.HotBeansGiveDto;
import com.xqboss.apps.enums.consumer.InteractMsgEnum;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.enums.mq.AppMqNormalEnum;
import com.xqboss.apps.enums.user.RealAuthStatusEnum;
import com.xqboss.apps.service.aliyun.AliFaceService;
import com.xqboss.apps.service.consumer.ConsumerRealNameService;
import com.xqboss.apps.service.equipment.EquipmentService;
import com.xqboss.apps.service.market.MarketService;
import com.xqboss.apps.service.order.PayApplyService;
import com.xqboss.apps.service.order.pay.impl.WalletPayExecutor;
import com.xqboss.apps.service.punch.UserPunchService;
import com.xqboss.apps.service.user.SysUserHotbeansRecordService;
import com.xqboss.apps.service.user.YeepayWalletService;
import com.xqboss.apps.vo.market.MarketListVo;
import com.xqboss.common.annotation.Anonymous;
import com.xqboss.common.annotation.RateLimiter;
import com.xqboss.common.config.XQBossConfig;
import com.xqboss.common.config.properties.SmsProperties;
import com.xqboss.common.constant.Constants;
import com.xqboss.common.core.domain.AjaxResult;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.common.core.domain.model.RegisterBody;
import com.xqboss.common.core.mq.MqSender;
import com.xqboss.common.enums.LimitType;
import com.xqboss.common.utils.SecurityUtils;
import com.xqboss.common.utils.SocketUtil;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.common.utils.spring.SpringUtils;
import com.xqboss.framework.web.service.SysLoginService;
import com.xqboss.framework.web.service.SysRegisterService;
import com.xqboss.system.service.ISysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

import static com.xqboss.common.core.domain.AjaxResult.error;

/**
 * @author Administrator
 */
@Api(tags = {"测试接口"})
@RestController
@RequestMapping("/debug")
public class DebugController {

    @Autowired
    private SysLoginService loginService;
    @Autowired
    private WalletPayExecutor walletPayExecutor;
    @Autowired
    private PayApplyService payApplyService;
    @Autowired
    private YeepayWalletService yeepayWalletService;
    @Autowired
    private SysRegisterService registerService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ConsumerRealNameService consumerRealNameService;
    @Autowired
    private AliFaceService aliFaceService;
    @Autowired
    private MarketService marketService;
    @Autowired
    private MqSender mqSender;

    @Autowired
    private SysUserHotbeansRecordService basicService;
    @Autowired
    private EquipmentService equipmentService;
    @Autowired
    private UserPunchService userPunchService;

    @Anonymous
    @ApiOperation("测试接口")
    @GetMapping("test")
    public R uploadFile() throws Exception {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        System.out.println(SmsProperties.KEY_ID);
        System.out.println(SmsProperties.KEY_SECRET);
        System.out.println(SmsProperties.REGION_Id);
//        if (SmsUtil.sendMsg("13688234834", "123456")) {
//            System.out.println("发送成功");
//        }
        String token = loginService.login("admin", "123456", null,
                "loginBody.getUuid()", true);
        return R.ok(token);
    }

    @Anonymous
    @ApiOperation("测试密码登录接口")
    @GetMapping("pwd-login")
    public R pwdLogin(@RequestParam String username, @RequestParam String password) throws Exception {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        System.out.println(SmsProperties.KEY_ID);
        System.out.println(SmsProperties.KEY_SECRET);
        System.out.println(SmsProperties.REGION_Id);
//        if (SmsUtil.sendMsg("13688234834", "123456")) {
//            System.out.println("发送成功");
//        }
        String token = loginService.login(username, password, null,
                "loginBody.getUuid()", true);
        return R.ok(token);
    }
    @ApiOperation("创建易宝钱包")
    @GetMapping("yeepay-create-wallet")
    public R createYpWallet() throws Exception {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        String url = yeepayWalletService.getWalletIndex(user);
        return R.ok(url);
    }

    @ApiOperation("测试钱包支付")
    @PostMapping("wallet-pay")
    public R walletPay(HttpServletRequest request, @Validated @RequestBody WalletPayDto dto) throws Exception {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        TradeResultDto resultDto = walletPayExecutor.verifyCallback(request, dto);
        payApplyService.paySuccess(resultDto);
        return R.ok();
    }

    @Anonymous
    @ApiOperation("添加用户，并自动实名")
    @PostMapping("add-user")
    public R addUser(@RequestBody RegisterBody body) throws Exception {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        String s = registerService.appRegister(body);
        if(StringUtils.isNotEmpty(s)){
            return R.fail(s);
        }
        SysUser user = sysUserService.selectUserByUserName(body.getUsername());
        if(user != null){
            ConsumerRealName realName = new ConsumerRealName();
            realName.setUserId(user.getUserId());
            realName.setIdCard("000000000000000");
            realName.setIdCardName("测试");
            realName.setIsFirstReal(true);
            realName.setAuthStatus(RealAuthStatusEnum.AUTH_SUCCESS);
            realName.setAuthTime(LocalDateTime.now());
            consumerRealNameService.save(realName);
        }
        sysUserService.resetUserPayPwd(user.getUserName(), SecurityUtils.encryptPassword("123456"));

        return R.ok(body.getUsername());
    }


    @ApiOperation("测试手机号验证码登录")
    @PostMapping("/verifyCode/login")
    @Anonymous
    public AjaxResult verifyLoginSmsCode(@RequestParam String username, @RequestParam String code) {
        if(!XQBossConfig.isTestEnable()){
            return error();
        }
        AjaxResult ajax = AjaxResult.success();
        if (StrUtil.isBlank(username) || StrUtil.isBlank(code)) {
            return error("手机号/验证码不能为空！");
        }
        // 生成令牌
        String token = loginService.login(username, null, code,
                "", true);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    @ApiOperation("websokcet链接推送消息")
    @GetMapping("pushToWeb/{userId}")
    @Anonymous
    public String pushToWeb(@PathVariable String userId, String message) {
        if(!XQBossConfig.isTestEnable()){
            return "";
        }
        SocketUtil.sendOneMessage(userId, SecurityUtils.getNickName() + ",+" + SecurityUtils.getAvatar(), InteractMsgEnum.TEAM_SETTLEMENT.getValue(), 998L);
        return "R.ok()";
    }

    private static final DataSource dataSource = SpringUtils.getBean(DataSource.class);

    @ApiOperation("批量插入")
    @GetMapping("saveData/{type}/{count}")
    public R pushToWeb(@PathVariable String type, @PathVariable Long count) throws SQLException {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        Connection connection = dataSource.getConnection();
        connection.setAutoCommit(false);

        String sql;
        PreparedStatement statement = null;

        if ("box".equals(type)) {
            sql = "INSERT INTO `box`(`id`, `name`,`headimg`, `price`, `type`, `stock`, `display_stock`, `saleable`, `publish_time_start`,`category_id`) VALUES(?,?,?,?,?,?,?,?,?,?) ";
            statement = connection.prepareStatement(sql);
            for (int i = 0; i < count; i++) {
                statement.setLong(1, IdUtil.getSnowflakeNextId());
                statement.setString(2, "name" + i);
                statement.setString(3, "http://zcyc-star-test.oss-cn-chengdu.aliyuncs.com/img/20230925/1695649247015.png");
                statement.setBigDecimal(4, BigDecimal.valueOf(i));
                statement.setInt(5, 1);
                statement.setInt(6, 99);
                statement.setInt(7, 88);
                statement.setInt(8, 1);
                statement.setDate(9, Date.valueOf(LocalDate.now()));
                statement.setInt(10, 771);
                statement.addBatch();
            }
        } else if ("punch_user_record".equals(type)) {

            sql = "INSERT INTO `punch_user_record`(`user_id`, `luck`, `talent`, `durable`, `strong`, `type`, `income`) VALUES (?,?,?,?,?,?,?)";
            statement = connection.prepareStatement(sql);
            for (int i = 0; i < count; i++) {
                statement.setLong(1, 1701772964171800576L);
                statement.setInt(2, i);
                statement.setInt(3, i);
                statement.setInt(4, i);
                statement.setInt(5, 998);
                statement.setInt(6, 1);
                statement.setInt(7, i);
                statement.addBatch();
            }
        } else if ("sys_user_wallet_record".equals(type)) {

            sql = "INSERT INTO `sys_user_wallet_record`(`user_id`, `wallet_id`, `wallet_type`, `amount`, `amount_after`, `amount_before`, `direction`,`change_type`,`remark`)VALUES (?,?,?,?,?,?,?,?,?)";
            statement = connection.prepareStatement(sql);
            for (int i = 0; i < count; i++) {
                statement.setLong(1, 1701577341501919232L);
                statement.setInt(2, 35);//钱包id
                statement.setInt(3, 1);//钱包类型
                statement.setInt(4, i);//变动金额
                statement.setInt(5, 998);//变动后金额
                statement.setInt(6, 1998);//变动前金额
                statement.setInt(7, 2);//变动方向  入 出
                statement.setInt(8, 3);//2 订单支付，3提现，4充值,7队伍收益
                statement.setString(9, "提现");//2 订单支付，3提现，4充值
                statement.addBatch();
            }
        } else {
            return R.fail("暂不支持此表类型");
        }


        long start = System.currentTimeMillis();
        try {
            statement.executeBatch();
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            statement.close();
            connection.close();
        }

        System.out.print("耗时：");
        System.out.println(System.currentTimeMillis() - start);
        return R.ok();
    }

    @ApiOperation("获取阿里云实名认证信息")
    @GetMapping("aliface-info")
    @Anonymous
    public R getAlifaceInfo(String certifyId) {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        DescribeFaceVerifyResponse faceVerifyStatus = aliFaceService.getFaceVerifyStatus(certifyId);
        return R.ok(faceVerifyStatus);
    }


    @ApiOperation("市场上架")
    @PostMapping("add-market")
    public R addMarket(@Validated @RequestBody AddMarketDto addMarketDto) {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        marketService.addMarket(SecurityUtils.getUserId(), addMarketDto);
        return R.ok();
    }

    @RateLimiter(key="market:", time = 24 * 60 * 60, count = 500, limitType = LimitType.IP)
    @ApiOperation("测试接口--典藏、装备、宝盒列表")
    @GetMapping("list")
    public R<List<MarketListVo>> list(@Validated MarketDto dto) {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        List<MarketListVo> voList = marketService.marketList(dto,10);
        return R.ok(voList);
    }

    @Anonymous
    @ApiOperation("测试接口--消息队列")
    @GetMapping("test-mq")
    public R testMq(String msg, Long time) {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        if(time == null){
            mqSender.send(AppMqNormalEnum.NORMAL_TEST, msg);
        }else{
            mqSender.sendDelay(AppMqDelayEnum.DELAY_TEST, msg, time);
        }
        return R.ok();
    }


    @ApiOperation("测试接口 - 测试转赠热豆")
    @PostMapping("test-hot-beans-give")
    public R testhotBeansGive(@RequestBody @Validated HotBeansGiveDto dto) {
        if(!XQBossConfig.isTestEnable()){
            return R.fail();
        }
        basicService.hotBeansGive(dto, SecurityUtils.getUserId());
        return R.ok();
    }

//    @ApiOperation("装备剩余空投计算")
//    @Anonymous
//    @GetMapping("test-hot-beans-give/{equipmentId}")
//    public R testhotBeansGive(@PathVariable Long equipmentId) {
////        if(!XQBossConfig.isTestEnable()){
////            return R.fail();
////        }
//        Equipment equipment = equipmentService.getById(equipmentId);
//        BigDecimal bigDecimal = userPunchService.calcPunchIncomeByWeaken(equipment, false);
//        return R.ok(bigDecimal);
//    }


}
